import Vue from 'vue';
const vm = new Vue();

//发送request,请求
const request = function(url, postData, method, type) {
	if(!type) type=false;
	if(!postData) 
	{
		type={};
		postData = {};
	}
	postData.token = getToken();
	postData.user_id = getUserId();
	//请求日志
	console.info("api请求:%s, method: %o, type: %s 参数: %o", url,  method, type, postData);
	//接口请求
	return new Promise((resolve, reject) => {
		console.log('当前传递的token:'+getToken())
		uni.request({
			url: url,
			data: postData,
			header: {'Content-Type': type ? type : 'application/json', 'authorization': getToken()},
			method: method ? method : 'POST', //'GET','POST'
			dataType: 'json',
			success: (res) => {
				console.log('api返回: %s\n结果: %o', url, res);
				if(res.statusCode === 500) {
					uni.showToast({
						title:"服务器开小差啦",
						icon:"none"
					})
					reject(res);
				}
				
				if(!res.data && !res.data.code) {
					uni.showToast({
						title:"服务器错误",
						icon:"none"
					})
					reject(res);
				}
				//服务端返回错误
				if(res.data.code == -1){
					uni.showToast({
						title:"服务器开小差啦",
						icon:"none"
					})
					reject(res);
				}
				//服务端返回错误
				if(res.data.code == 100401 || res.data.code == 100402 || res.data.code == 100403){
					vm.$store.dispatch("Logout");
					uni.navigateTo({
						url:'../pages/public/login'
					})
				}
				resolve(res.data)
			},
			fail: (err) => {
				console.log('api请求出错: %o', err);
				reject(err)
			}
		});
	})
}

//获取当前token
const getToken = function() {
	return uni.getStorageSync("token")
}
//获取当前user_id
const getUserId = function() {
	return uni.getStorageSync("userid")
}

module.exports = {
	request
}